<template>
    <el-drawer v-model="show" :title="title" size="70vw">
        <el-row>
            <el-col :span="24">
                <el-form ref="formRef" :model="formData" label-width="120" :rules="rules" v-loading="loading">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="区域类型" prop="areaType">
                                <el-radio-group v-model="formData.areaType">
                                    <el-radio-button label="国家行政区域" value="GOV" />
                                    <el-radio-button label="自定义" value="CUSTOM" disabled/>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" v-if="formData.areaType === 'GOV'">
                        <el-col :span="12">
                            <el-form-item label="城市" prop="city">
                                 <el-cascader v-model="formData.city" :options="cityOptions" placeholder="请选择城市" style="width: 100%;" @change="changeCity" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" v-if="formData.areaType === 'CUSTOM'">
                        <el-col :span="12">
                            <el-form-item label="区域代码" prop="areaCode">
                                 <el-input v-model="formData.areaCode" placeholder="请输入区域代码" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="区域名称" prop="areaCode">
                                 <el-input v-model="formData.areaCode" placeholder="请输入区域名称" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-col>
        </el-row>
        <template #footer>
            <div class="footer-row">
                <el-button type="primary" @click="preSave" :loading="loading">保存</el-button>
                <el-button @click="closeDrawer" :loading="loading">关闭</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { usePickerStore } from '../../../store/picker'
import { useAreaStore } from '../../../store/area'
import { areaList } from '@vant/area-data';
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'

const pickerStore = usePickerStore()

const areaStore = useAreaStore()

const props = defineProps({
  show: Boolean,
  detailData: Object
})
const emit = defineEmits(['update:show', 'close'])

const show = computed<boolean>({
  get: () => props.show,
  set: val => emit('update:show', val)
})
const formRef = ref<FormInstance>()
const rules = {
    areaType: [
        { required: true, message: '请选择区域类型', trigger: 'blur' },
    ],
    city: [
        { required: true, message: '请选择区域类型', trigger: 'blur' },
    ],
    areaCode: [
        { required: true, message: '请输入区域代码', trigger: 'blur' },
    ],
    areaName: [
        { required: true, message: '请输入区域名称', trigger: 'blur' },
    ]
}
const title = ref<string>('');
const loading = ref<boolean>(false);
const formData = ref<any>({});
const cityOptions = ref<any[]>([]);
let systemCityList:any[] = []

watch(() => props.detailData, () => {
    initData()
    getAreaList()
    loading.value = false
},{deep: true})
watch(() => show, () => {
    if (!show.value) {
        emit('close')
    }
}, {deep: true})
function getAreaList() {
    pickerStore.getAreaList({}).then((res) => {
        if (res.code === 't_200') {
            systemCityList = [...res.obj || []]
        }
    }).finally(() => {
        initCityList()
    })
}
function initCityList() {
    const cityData = {...areaList || {}}
    let province = cityData.province_list
    let city = cityData.city_list
    let listData = []
    let provinceData:any = {}
    for (let key in city) {
        let code = key.slice(0, 2)
        let provinceCode = code + "0000"
        if (!provinceData[provinceCode]) {
            provinceData[provinceCode] = []
        }
        let index = systemCityList.findIndex((item) => item.code === key)
        provinceData[provinceCode].push({
            value: key,
            label: city[key],
            disabled: index !== -1
        })
    }

    for (let key in province) {
        let item = {
            value: key,
            label: province[key],
            children: provinceData[key] || []
        }
        listData.push(item)
    }
    cityOptions.value = listData
}
function initData() {
    let data = {...props.detailData || {}}
    if (data.id){
        title.value = '编辑区域'
        let areaCode = data.areaCode
        let province = areaCode.slice(0, 2) + '0000'
        let city = areaCode.slice(0, 4) + '00'
        formData.value = {
            city: [province, city],
            areaType: data.areaType,
            areaCode: data.areaCode,
            areaName: data.areaName
        }
    } else {
        title.value = '新增区域'
        formData.value = {}
    }
}
function closeDrawer() {
    show.value = false
}
function changeCity(value:any) {
    let city = value[value.length - 1]
    const areaData = {...areaList || {}}
    let cityList = areaData.city_list
    let cityName = cityList[city]
    formData.value.areaCode = city
    formData.value.areaName = cityName
}
function preSave() {
    formRef.value?.validate((valid) => {
        if (valid) {
            doSave()
        }
    })
}
function doSave() {
    loading.value = true
    let detailData = {...props.detailData || {}}
    let data = {...formData.value}
    let params = {
        id: detailData.id || '',
        areaType: data.areaType,
        areaCode: data.areaCode,
        areaName: data.areaName
    }
    areaStore.saveArea(params).then((res) => {
        if (res.code === 't_200') {
            ElMessage.success('保存成功！')
            closeDrawer()
        } else {
            ElMessage.error(res.msg)
        }
    }).catch(() => {
        ElMessage.error("网络异常")
    }).finally(() => {
        loading.value = false
    })
}
</script>
<style lang="scss" scoped>

.footer-row{
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
</style>
